﻿Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Shapes
Imports Microsoft.Phone.Controls
Imports System.Net.NetworkInformation
Imports System.Threading
Imports System.Xml.Linq
Imports <xmlns:atom="http://www.w3.org/2005/Atom">
Imports <xmlns:media="http://search.yahoo.com/mrss/">
Imports <xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/">
Imports <xmlns:gd="http://schemas.google.com/g/2005">
Imports <xmlns:gml="http://www.opengis.net/gml">
Imports <xmlns:yt="http://gdata.youtube.com/schemas/2007">
Imports <xmlns:georss="http://www.georss.org/georss">

Partial Public Class MainPage
    Inherits PhoneApplicationPage
    ' Constructor
    Public Sub New()
        InitializeComponent()
    End Sub

    Public Property RSSSources As New List(Of RSSSource)

    Private Sub MainPage_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles Me.Loaded
        Me.ApplicationBar.IsVisible = False
        VisualStateManager.GoToState(Me, "Loading", True)
        SystemTray.SetBackgroundColor(Me, CType(App.Current.Resources("AppBackground"), SolidColorBrush).Color)

        RSSSources.Add(New RSSSource() With {.Name = "Daron Blog", .Source = "http://feeds2.feedburner.com/daronyondem", .SourceType = RSSSource.SourceTypes.RSS})
        RSSSources.Add(New RSSSource() With {.Name = "Twitter", .Source = "http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=daronyondem&count=10", .SourceType = RSSSource.SourceTypes.Twitter})
        RSSSources.Add(New RSSSource() With {.Name = "Facebook!", .Source = "https://www.facebook.com/feeds/page.php?id=207889319255642&format=rss20", .SourceType = RSSSource.SourceTypes.Facebook})
        RSSSources.Add(New RSSSource() With {.Name = "YouTube!", .Source = "http://gdata.youtube.com/feeds/api/users/daronyondem/uploads?v=2",
                                             .SourceType = RSSSource.SourceTypes.YouTube})

        InitialShow()
    End Sub

    Dim InitialDownloadIndex As Integer = 0

    Sub InitialShow()
        Dim RSSS = RSSSources(InitialDownloadIndex)
        Dim NewItem As New PivotItem
        NewItem.Margin = New Thickness(0, 0, 0, 70)
        NewItem.Header = RSSS.Name
        Dim RSSListControl As New RSSList(RSSS.Source, RSSS.Name)
        RSSS.UIRepresenter = RSSListControl
        NewItem.Content = RSSListControl
        MainPivot.Items.Add(NewItem)
        AddHandler RSSListControl.DoDownloadComplete, Sub()
                                                          InitialLoadTransform.ScaleX = 1 - ((1 / RSSSources.Count) * (InitialDownloadIndex + 1))
                                                          If InitialDownloadIndex = RSSSources.Count - 1 Then
                                                              VisualStateManager.GoToState(Me, "Loadedd", True)
                                                              Me.ApplicationBar.IsVisible = True

                                                              'If the app was running for the first time
                                                              If System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Contains("Boot") = False Then
                                                                  System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Add("Boot", "Done")
                                                                  Refresh_Click(Nothing, Nothing)
                                                              End If
                                                              Exit Sub
                                                          End If
                                                          InitialDownloadIndex += 1
                                                          InitialShow()
                                                      End Sub
        RSSListControl.DownloadRSS()
    End Sub

    Private Sub Refresh_Click(sender As System.Object, e As System.EventArgs)
        Me.ApplicationBar.IsVisible = False
        LoadText_Left.Text = "0"
        LoadText_Right.Text = RSSSources.Count
        LoadBar.Visibility = Windows.Visibility.Visible
        ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf DoDownload), RSSSources.ToList())
    End Sub

    Private Sub DownloadCompleted(sender As Object, e As DownloadStringCompletedEventArgs)
        Dim InnerRSSSources As List(Of RSSSource) = e.UserState
        Dim CurrentRSSSource = InnerRSSSources(0)
        Dim All As New List(Of RSSItem)

        Try
            Dim ResultString As String = e.Result
            Dim XMLDoc As XDocument = XDocument.Parse(ResultString)

            If CurrentRSSSource.SourceType = RSSSource.SourceTypes.Atom Then
                All = (From inc In XMLDoc.<atom:feed>.<atom:entry> Select New RSSItem() With {.Title = inc.<atom:title>.Value,
                                                                                            .Description = System.Net.HttpUtility.HtmlDecode(PhoneHelpers.HTML.StripTagsAndAttributes(inc.<atom:summary>.Value, New String() {})),
                                                                                            .Link = inc.<atom:link>.Value}).ToList()
            ElseIf CurrentRSSSource.SourceType = RSSSource.SourceTypes.RSS Then
                All = (From inc In XMLDoc.<rss>.<channel>.<item> Select New RSSItem() With {.Title = inc.<title>.Value,
                                                                                            .Description = PhoneHelpers.HTML.StripTagsAndAttributes(inc.<description>.Value, New String() {}),
                                                                                            .Link = inc.<link>.Value}).ToList()
            ElseIf CurrentRSSSource.SourceType = RSSSource.SourceTypes.Twitter Then
                All = (From inc In XMLDoc.<statuses>.<status> Select New RSSItem() With {.Title = inc.<text>.Value,
                                                                                         .Description = "",
                                                                                         .Link = ""}).ToList()
            ElseIf CurrentRSSSource.SourceType = RSSSource.SourceTypes.Facebook Then
                All = (From inc In XMLDoc.<rss>.<channel>.<item> Select New RSSItem() With {.Title = System.Net.HttpUtility.HtmlDecode(inc.<title>.Value),
                                                                                            .Description = System.Net.HttpUtility.HtmlDecode(PhoneHelpers.HTML.StripTagsAndAttributes(inc.<description>.Value, New String() {})),
                                                                                            .Link = inc.<link>.Value}).ToList()
            ElseIf CurrentRSSSource.SourceType = RSSSource.SourceTypes.YouTube Then
                All = (From inc In XMLDoc.<atom:feed>.<atom:entry> Select New RSSItem() With {.Title = inc.<atom:title>.Value,
                                                                                            .Description = System.Net.HttpUtility.HtmlDecode(PhoneHelpers.HTML.StripTagsAndAttributes(inc.<media:group>.<media:description>.Value, New String() {})),
                                                                                            .Link = String.Format("http://www.youtube.com/embed/{0}?autoplay=1", inc.<media:group>.<yt:videoid>.Value)}).ToList()
            End If
        Catch ex As Exception

        End Try

        Dim UIRepresenter = CType(InnerRSSSources(0).UIRepresenter, RSSList)
        PhoneHelpers.IsolatedStorage.SaveToIsolatedStorage(Of List(Of RSSItem))(All, CurrentRSSSource.Name)
        Dispatcher.BeginInvoke(Sub()
                                   UIRepresenter.ShowList(All)
                               End Sub)
        InnerRSSSources.RemoveAt(0)

        If InnerRSSSources.Count > 0 Then
            Dispatcher.BeginInvoke(Sub()
                                       LoadText_Left.Text = CInt(LoadText_Right.Text) - InnerRSSSources.Count
                                   End Sub)
            DoDownload(InnerRSSSources)
        Else
            Dispatcher.BeginInvoke(Sub()
                                       Me.ApplicationBar.IsVisible = True
                                       LoadBar.Visibility = Windows.Visibility.Collapsed
                                   End Sub)
        End If
    End Sub

    Private Sub DoDownload(InnerRSSSources As List(Of RSSSource))
        If NetworkInterface.GetIsNetworkAvailable Then
            Dim XSource = InnerRSSSources(0)
            Dim Webc As New WebClient
            AddHandler Webc.DownloadStringCompleted, AddressOf DownloadCompleted
            If NetworkInterface.GetIsNetworkAvailable Then
                Webc.DownloadStringAsync(New Uri(XSource.Source, UriKind.Absolute), InnerRSSSources)
            Else
                Dispatcher.BeginInvoke(Sub()
                                           Me.ApplicationBar.IsVisible = True
                                           LoadBar.Visibility = Windows.Visibility.Collapsed
                                           MessageBox.Show("No internet connectivity!")
                                       End Sub)
                Exit Sub
            End If
        Else
            Dispatcher.BeginInvoke(Sub()
                                       Me.ApplicationBar.IsVisible = True
                                       LoadBar.Visibility = Windows.Visibility.Collapsed
                                       MessageBox.Show("No internet connectivity!")
                                   End Sub)
        End If
    End Sub

End Class
